package makabakaquestionnaire.zutsoftware.framework.captcha.core;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.IdUtil;
import makabakaquestionnaire.zutsoftware.constant.Constants;
import makabakaquestionnaire.zutsoftware.constant.Result;
import makabakaquestionnaire.zutsoftware.utils.redis.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author ：wjf
 * @date ：Created in 2022/2/21 14:53
 * @description：验证码生成接口
 * @modified By：
 */
@RestController
public class CaptchaController {
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    CaptchaProperties captchaProperties;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public Result getCode(HttpServletResponse response) throws IOException {
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight(), 4, 20);
        String uuid = IdUtil.fastSimpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        redisUtils.set(verifyKey, captcha.getCode(), captchaProperties.getTimeout(), TimeUnit.MINUTES);
        Console.log(captcha.getCode());
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            // 转换流信息写出
            BufferedImage image = captcha.getImage();
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        HashMap data = new HashMap();
        data.put("uuid", uuid);
        data.put("img", Base64.encode(os.toByteArray()));
        return Result.success(data, "请查看验证码");
    }
}
